package sessionbean;

import java.io.BufferedInputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.Stateless;

@Stateless
public class HTMLDownloaderSession {
    private static final Logger logger = Logger.getLogger(HTMLDownloaderSession.class.getName());
    
    public String processURL(String url) {
        try {
            return processURL(new URL(url));
        } catch (MalformedURLException ex) {
            logger.log(Level.SEVERE, null, ex);
            return "";
        }
    }
    
    public String processURL(URL url) {
        try {
            logger.log(Level.INFO, "Getting html for url {0}.", url);
            BufferedInputStream inputStream = new BufferedInputStream(url.openStream());
            int toRead = 0;
            StringBuilder stringBuilder = new StringBuilder();
            while ((toRead = inputStream.read()) != -1) {
                stringBuilder.append((char) toRead);
            }
            return stringBuilder.toString();
        } catch (Exception ex) {
            logger.log(Level.SEVERE, null, ex);
            return "";
        }
    }
}
